const BaseController = require("./base/base");
const Result = require("../utils/result");
const tools = require("../utils/tools");
const jwt = require("jsonwebtoken");
const UsersModel = require("../model/users");
var svgCaptcha = require('svg-captcha');
const { getTokenUser, isAdmin } = require("../middlewares/auth");
class UsersController extends BaseController {
  constructor() {
    super();
    this.key = "xiaohuai";
  }
  // 登录
  login(req, res, next) {
    setTimeout(async () => {
      try {
        const { username, password } = req.body;
        console.log(username, password);
        if (!username || !password) return res.json(Result.fail("用户名或密码错误"));
        let userinfo = await UsersModel.findOne({ username, password });
        console.log(userinfo);
        if (!userinfo || userinfo.length == 0) return res.json(Result.fail("用户名或密码错误"));
        // if (userinfo.state != true) return res.json(Result.fail("用户已禁用"));
        const authorization = jwt.sign({ _id: userinfo._id, username }, this.key, { expiresIn: "1d" });
        res.json(Result.ok("success", { _id: userinfo._id, username, authorization }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 验证
  verify(req, res, next) {
    setTimeout(async () => {
      try {
        const { authorization } = req.headers; //headers 里面的所有key都会是小写
        if (!authorization) return res.json(Result.fail("authorization错误"));
        const data = jwt.verify(authorization, this.key); //{"user_name":"admin","iat":1635349069,"exp":1635435469}
        res.json(Result.ok("success", data));
      } catch (err) {
        //篡改{"name":"JsonWebTokenError","message":"invalid token"}
        //过期{"name":"TokenExpiredError","message":"jwt expired","expiredAt":"2021-10-28T03:28:45.000Z"}
        res.json(Result.fail(err));
      }
    })
  }
  // 验证码
  captcha(req, res, next) {
    setTimeout(async () => {
      const { width = "120", height = "40" } = req.query;
      var codeConfig = { size: 4, ignoreChars: 'abh0QOoqg9l1iv', noise: 2, color: true, };
      if (width) codeConfig["width"] = width;
      if (height) codeConfig["height"] = height;
      var captcha = svgCaptcha.create(codeConfig);
      req.session.captcha = captcha.text.toLowerCase();
      res.set('Content-Type', 'image/svg+xml');
      res.send(captcha.data);
    })
  }
  vcaptcha(req, res, next) {
    setTimeout(async () => {
      try {
        let { vcode } = req.params;
        let { captcha } = req.session;
        console.log(vcode, captcha);
        if (!vcode || !captcha) return res.json(Result.fail("没有验证码"));
        captcha = captcha.toLowerCase();
        vcode = vcode.toLowerCase();
        if (vcode != captcha) return res.json(Result.fail("验证码错误"));
        res.json(Result.ok());
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 获取用户列表
  findUsersList(req, res, next) {
    setTimeout(async () => {
      try {
        let { pagesize = 5, page = 1, username = '', class_grade = '', role = '' } = req.query;
        pagesize *= 1
        page *= 1
        // 页码对应的数据查询开始位置
        let start = (page - 1) * pagesize;
        // 将用户信息从数据库中查询出来
        let username_filter = {};
        let role_filter = {};
        let class_grade_filter = {};


        if (username) username_filter = { username: { $regex: username, $options: 'i' } }
        if (role) role_filter = { role: { $regex: role, $options: 'i' } }
        if (class_grade) class_grade_filter = { class_grade: { $regex: class_grade, $options: 'i' } }

        let _filter = Object.assign(username_filter, role_filter, class_grade_filter)
        let list = await UsersModel.find(_filter).limit(pagesize).skip(start)
        let total = await UsersModel.countDocuments(_filter)
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 增加用户
  insert(req, res, next) {
    setTimeout(async () => {
      try {
        let { username, password, sex = 1, tel = '', class_grade = '', organization = '', state = 1, role = "用户", add_time = '' } = req.body;
        if (!isAdmin(role)) { role = "用户" } //处理角色字段
        if (!(username && password)) return res.json(Result.fail("用户名和密码不能为空"));
        let ret = await UsersModel.findOne({ username });
        if (ret) return res.json(Result.fail("用户名已存在"));
        ret = await UsersModel.create({ username, password, sex, tel, class_grade, organization, state, role, add_time });
        res.json(!ret._id ? Result.fail("添加失败") : Result.ok("添加成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 获取单个用户信息
  findById(req, res, next) {
    setTimeout(async () => {
      try {
        let { id } = req.params;
        let ret = await UsersModel.findOne({ _id: id });
        res.json(Result.ok("success", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 修改用户信息
  updateuser(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await UsersModel.updateOne({ _id: id }, req.body);
        // if (!ret.matchedCount) return res.json(Result.fail("修改失败", ret))
        res.json(!ret.matchedCount ? Result.fail("修改失败", ret) : Result.ok("修改成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 删除用户
  delById(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await UsersModel.deleteOne({ _id: id });
        res.json(!ret.deletedCount ? Result.fail("删除失败") : Result.ok("删除成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 修改密码
  editpwd(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;  //用户ID
        const { password, newpassword } = req.body;
        if (!password) return res.json(Result.fail("原密码不能为空"));
        if (!newpassword) return res.json(Result.fail("新密码不能为空"));
        let ret = await UsersModel.findById(id);
        if (!ret) return res.json(Result.fail("用户不存在"));
        if (password != ret.password) return res.json(Result.fail("原密码错误"));
        ret = await UsersModel.updateOne({ _id: id }, { password: newpassword });
        res.json(!ret.modifiedCount ? Result.fail("修改失败") : Result.ok("修改成功"))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new UsersController().resolve();